﻿using System;
using System.Web.UI.WebControls;
using DBProvider;
using DBProvider.Providers;

namespace HealthCommunity.Controls
{
	public partial class UCActivityNewest : System.Web.UI.UserControl
	{
		private IActivityProvider _ActivityProvider;

		protected void Page_Load(object sender, EventArgs e)
		{
			//if (!IsPostBack)
			{
				BindData();
			}
		}

		protected void rptNewActivity_ItemDataBound(object sender, RepeaterItemEventArgs e)
		{
			if (e.Item.DataItem != null)
			{
				var hlActivity = e.Item.FindControl("hlActivity") as HyperLink;
				var ltrActivityDescription = e.Item.FindControl("ltrActivityDescription") as Literal;
				var ltrUserCount = e.Item.FindControl("ltrUserCount") as Literal;
				var ltrActivityStartTime = e.Item.FindControl("ltrActivityStartTime") as Literal;

				var dataItem = e.Item.DataItem as Activity;

				hlActivity.Text = dataItem.ActivityTitle;
				hlActivity.NavigateUrl = "~/ActivityDetail.aspx?activityid=" + dataItem.ActivityID.ToString();
				ltrActivityStartTime.Text = "开始时间: " + dataItem.ActivityStartTime.Value.ToShortDateString();
				ltrActivityDescription.Text = dataItem.ActivityDescription;
				if (!string.IsNullOrEmpty(dataItem.ActivityDescription) && dataItem.ActivityDescription.Length > 45)
				{
					ltrActivityDescription.Text = dataItem.ActivityDescription.Substring(0, 45) + "...";
				}
				if (dataItem.ActivityTitle.Length > 15)
				{
					hlActivity.Text = dataItem.ActivityTitle.Substring(0, 15) + "...";
				}
				hlActivity.ToolTip = dataItem.ActivityTitle;
				if (dataItem.RLT_ACTIVITYANDUSERs != null && dataItem.RLT_ACTIVITYANDUSERs.Count > 0)
				{
					ltrUserCount.Text = "已报名人数: " + dataItem.RLT_ACTIVITYANDUSERs.Count.ToString();
				}
				else
				{
					ltrUserCount.Text = "已报名人数: 0";
				}
			}
		}

		private void BindData()
		{
			if (_ActivityProvider == null)
			{
				_ActivityProvider = new ActivityProvider();
			}

			var user = SiteContext.Current.CurrentUser;

			if (user != null && user.Role != null && user.Role.RoleName.Equals("admin"))
			{
				var drugStore = SiteContext.Current.CurrentDrugStore;

				if (drugStore != null)
				{
					rptNewActivity.DataSource = _ActivityProvider.GetNewActivities(6, drugStore.DrugStoreID);
					rptNewActivity.DataBind();
				}
			}
			else
			{
				if (user != null && user.DrugStoreID.GetValueOrDefault(0) > 0)
				{
					rptNewActivity.DataSource = _ActivityProvider.GetNewActivities(6, user.DrugStoreID.GetValueOrDefault(0), user.UserID);
					rptNewActivity.DataBind();
				}
			}
		}
	}
}